// API 基础配置
const API_BASE_URL = 'http://localhost:8877'; // 根据实际后端地址修改

interface AuthResponse {
  token: string;
}

interface EmailVerifyResponse {
  token: string;
}

// API 请求参数类型定义
interface RegisterParams {
  email: string;
  password: string;
  code: string;
}

interface LoginParams {
  email: string;
  password: string;
}

interface SendEmailCodeParams {
  email: string;
}

// 错误处理函数
const handleApiError = (error: any) => {
  console.error('API Error:', error);
  throw new Error(error.message || '请求失败，请重试');
};

// 通用请求函数
const fetchApi = async <T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> => {
  try {
    const token = localStorage.getItem('token');
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...options.headers,
    };

    const response = await fetch(`${API_BASE_URL}${endpoint}`, {
      ...options,
      headers,
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.message || '请求失败');
    }

    return data;
  } catch (error) {
    return handleApiError(error);
  }
};

// API 函数
export const api = {
  // 注册
  async register(params: RegisterParams): Promise<string> {
    console.log(params);
    const response = await fetchApi<AuthResponse>('/register', {
      method: 'POST',
      body: JSON.stringify(params),
    });

    const { token } = response;
    localStorage.setItem('token', token);
    return token;
  },

  // 登录
  async login(params: LoginParams): Promise<string> {
    console.log(params);
    const response = await fetchApi<AuthResponse>('/token', {
      method: 'POST',
      body: JSON.stringify(params),
    });

    const { token } = response;
    localStorage.setItem('token', token);
    return token;
  },

  // 发送邮箱验证码
  async sendEmailCode(params: SendEmailCodeParams): Promise<void> {
    await fetchApi<EmailVerifyResponse>('/sendcode', {
      method: 'POST',
      body: JSON.stringify(params),
    });
  },

  // 验证 token 是否有效
  async verifyToken(): Promise<boolean> {
    try {
      await fetchApi('/verify', {
        method: 'GET',
      });
      return true;
    } catch {
      return false;
    }
  },

  // 退出登录
  logout(): void {
    localStorage.removeItem('token');
    localStorage.removeItem('userEmail');
  },
};

// Token 相关工具函数
export const token = {
  get(): string | null {
    return localStorage.getItem('token');
  },

  set(token: string): void {
    localStorage.setItem('token', token);
  },

  remove(): void {
    localStorage.removeItem('token');
  },

  exists(): boolean {
    return !!this.get();
  },
}; 